﻿using LSW_Shop.Models;
using LSW_Shop.Models.Database;
using LSW_Shop.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LSW_Shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly LSW_ShopContext _db;
        private readonly IJWTService _jwtService;
        /// <summary>
        /// 构造注入 从IOC获取服务过程
        /// </summary>
        /// <param name="db"></param>
        /// <param name="jwtService"></param>
        public UserController(LSW_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        //用户注册（用户使用手机号码，密码进行注册，密码需要二次确认）
        /// <summary>
        /// 注册接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string AddUser(AddUserRequest request)
        {
            if (request.Password != request.CirPassword)
                return "两次密码不一致";

            //判断手机号是唯一的 不能重复
            if (_db.Users.Any(x => x.Mobile == request.Mobile))
                return "手机号码已存在";

            //添加一个新的用户
            var user = new User
            {
                Createtime = DateTime.Now,
                Mobile = request.Mobile,
                Password = request.Password,
                NickName = string.Empty,
                Photo = string.Empty,
            };
            _db.Users.Add(user);
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";

        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //用户登录（用户使用手机号码，密码进行登录，登录后可访问需要授权的页面）
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //查询数据库有无这个用户 
            var user = _db.Users.FirstOrDefault(x => x.Mobile == request.Mobile);
            if (user == null)
                return "用户不存在";

            //验证密码
            //  123             不相等    "123                      "
            if (request.Password != user.Password)
                return "密码错误";


            var token = _jwtService.CreateToken(user.UserId, user.NickName);

            //返回token
            return token;
        }


        //个人中心（需要查询用户各订单状态数量，用户头像，用户昵称（如果没有设置昵称用手机号码代替））
        /// <summary>
        /// 个人中心（登录用户信息）
        /// </summary>
        /// 接口需要授权 获取登录用户
        [Authorize]
        [HttpPost]
        public GetUserInfoResponse GetUserInfo()
        {
            //获取登录信息
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;
            //用户头像，用户昵称

            return new GetUserInfoResponse
            {
                Photo = user.Photo,
                //   如果没有设置昵称用手机号码代替           三元运算符
                NickName = string.IsNullOrEmpty(user.NickName) ? user.Mobile : user.NickName
            };
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //修改用户信息（需要修改头像，用户昵称）
        [Authorize]
        [HttpPost]
        public string UpdateUser(UpdateUserRequest request)
        {
            //修改用户？

            //找用户
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return "用户不存在";

            user.Photo = request.Photo;
            user.NickName = request.NickName;
            _db.Users.Update(user);
            var row = _db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
    }

}
